#!/usr/bin/env python
# -*- coding: utf-8 -*-

import memcache
from .hash_ring import HashRing
from Settings.config import Config

ring = HashRing(Config.CACHE_MEMCACHED_SERVERS)

"""memcache缓存管理器，采用一致性hash算法计算存取缓存节点"""


class MemcacheManager(object):

    def get(self, key):
        server_node = ring.get_node(key)
        mc = memcache.Client([server_node])

        return mc.get(key)

    def set(self, key, value, time=Config.CACHE_MEMCACHED_EXPTIME):
        server_node = ring.get_node(key)
        mc = memcache.Client([server_node])

        return mc.set(key, value, time)

    def delete(self, key):
        server_node = ring.get_node(key)
        mc = memcache.Client([server_node])

        return mc.delete(key)
